package com.kaibes.admin.permission;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kaibes.web.permission.PermissionChecker;
import com.kaibes.web.thymeleaf.ThymeleafConfig;
import com.kaibes.web.util.WebUtils;

@Component
public class PermissionUtils implements InitializingBean {

	@Autowired
    private ThymeleafConfig thymeleafConfig;
	
	@Autowired
	private PermissionChecker permissionChecker;
	
	public boolean check(Integer userId, String name) {
		return permissionChecker.hasPermission(userId, name);
	}
	
	public boolean check(Integer userId, String uri, String method) {
		return permissionChecker.hasPermission(userId, uri, method);
	}
	
	public boolean checkGet(Integer userId, String uri) {
		return permissionChecker.hasPermission(userId, uri, "GET");
	}
	
	public boolean checkGet(String uri) {
		Integer userId = WebUtils.getAttribute("userId");
		return permissionChecker.hasPermission(userId, uri, "GET");
	}
	
	public boolean checkPost(String uri) {
		Integer userId = WebUtils.getAttribute("userId");
		return permissionChecker.hasPermission(userId, uri, "POST");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		thymeleafConfig.putStaticVariable("permissionUtils", this);
	}
    
}
